package com.um.jdy.app.charge.scheduled;

import cn.hutool.core.util.StrUtil;
import com.um.jdy.app.charge.manager.PBOrderManager;
import com.um.jdy.common.charge.entity.po.Order;
import com.um.jdy.common.charge.enums.OrderEnum;
import com.um.jdy.common.charge.service.OrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Profile;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * @author 甘天伟
 * @since 2022/4/23
 * 版权所有 广州优匠科技有限公司
 */
@Slf4j
@Component
@Profile({"!dev"})
public class PBOrderTask {

    @Autowired
    OrderService orderService;

    @Autowired
    PBOrderManager pbOrderManager;

    /**
     * 30分钟自动计费一次，订单时长超时，自动结束订单
     */
    @Async
    @Scheduled(fixedRate = 30 * 60 * 1000, initialDelay = 60000)
    public void autoTiming() {
        log.info("开始执行充电宝自动计时、计费定时任务 >>>>>>>>>>");

        List<Order> orderList = orderService.getListBySqlName("get_pb_order_list_by_status",
                new String[]{OrderEnum.Status.Charging.name()});

        orderList.forEach(order -> {
            try {
                pbOrderManager.autoTiming(order);
                log.info(StrUtil.format("充电宝订单[%s]已完成自动计时、计费", order.getOrderNo()));
            } catch (Exception ex) {
                log.error(StrUtil.format("充电宝订单[%s]自动计时、计费定时出错", order.getOrderNo()), ex);
            }
        });
    }


}
